#!/usr/bin/env bash

# This is scripts run after code is updated, so it's living as the target version not the previous old version,
# it allows one roundtrip upgrade.

echo "Upgrade living SRS_UTEST=$SRS_UTEST and ARGS: $*"

# Get the metadata of machine.
if [[ -f .env ]]; then source .env; fi
echo "LoadEnv CLOUD=$CLOUD REGION=$REGION, SOURCE=$SOURCE"

# Ignore darwin
if [[ ! -d /usr/local/srs-cloud && $(uname -s) == 'Darwin' ]]; then
  echo "Directly finish upgrade for macOS development"
  sleep 3; exit 0;
fi

# Prepare the OS again.
bash auto/upgrade_prepare "$@"
if [[ $? -ne 0 ]]; then echo "Prepare OS failed"; exit 1; fi

# Upgrade the react ui and restart mgmt service, ignore for utest.
if [[ $SRS_UTEST == true ]]; then
  echo "Ignore UI and mgmt service upgrade for utest"
else
  # Upgrade the react UI.
  # Note that new UI is built in platform docker image, so it's kept only for compatible reason.
  bash auto/upgrade_ui

  # Compatible with previous version.
  if [[ -d /usr/local/lighthouse/softwares/srs-terraform && ! -d /usr/local/lighthouse/softwares/srs-cloud ]]; then
    echo "Create link /usr/local/lighthouse/softwares/srs-cloud"
    ln -sf /usr/local/lighthouse/softwares/srs-terraform /usr/local/lighthouse/softwares/srs-cloud
  fi
  if [[ -d /usr/local/srs-terraform && ! -d /usr/local/srs-cloud ]]; then
    echo "Create link /usr/local/srs-cloud"
    ln -sf /usr/local/srs-terraform /usr/local/srs-cloud
  fi

  # Change permissions before restart.
  if [[ $(id -un lighthouse 2>/dev/null) == 'lighthouse' ]]; then
    echo "Change permissions for generated files"
    # Note that we keep files as root, because we run srs-cloud as root, see https://stackoverflow.com/a/70953525/17679565
    chown lighthouse:lighthouse /usr/local/srs-cloud/mgmt/.env
    if [[ $? -ne 0 ]]; then echo "Link files failed"; exit 1; fi
  fi

  echo "Restart service"
  if [[ -f /usr/lib/systemd/system/srs-cloud.service ]]; then
    systemctl daemon-reload && systemctl restart srs-cloud
  elif [[ -f /usr/lib/systemd/system/srs-terraform.service ]]; then
    systemctl daemon-reload && systemctl restart srs-terraform
  fi
  if [[ $? -ne 0 ]]; then echo "Restart service failed"; exit 1; fi
fi

echo "Living upgrade OK"

